<template>
  <el-container :showFooter="true" :autoFixHeight="true">
    <el-header>
      <div style="margin-top: 20px;">
        <el-page-header @back="back">
          <template slot="title">返回列表</template>
          <template slot="content">
            <el-button type="success" icon="el-icon-check" v-on:click="save">保存</el-button>
            <el-button type="primary" icon="el-icon-s-grid" v-on:click="showModules=true">扩展管理</el-button>
            <mf-exporter type="warning" :exporterName="model.name" text="导出测试"></mf-exporter>
          </template>
        </el-page-header>
      </div>
    </el-header>
    <el-main>
      <el-container>
        <el-header style="height: auto;">
          <el-form :model="model" label-width="200px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="导出名称">
                  <el-input v-model="model.name" disabled autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="数据加载器">
                  <el-input v-model="model.dataLoader" placeholder="请设置数据加载器"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="单表最大行数">
                  <el-input-number v-model="model.maxRowCountPerSheet"  :step="100" :min="100" :max="maxRowCount"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="Excel文件格式">
                  <el-select v-model="model.excelFormat" placeholder="请选择文件格式">
                    <el-option label="XLS" value="XLS" ></el-option>
                    <el-option label="XLSX" value="XLSX" ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="API地址">{{ previewLink }}</el-form-item>
              </el-col>
            </el-row>
          </el-form>

        </el-header>
        <el-main>
          <el-tabs v-model="currentTab" type="card" editable @edit="editSheet">
            <el-tab-pane v-for="(sheet, index) in model.sheets" :key="sheet.name" :label="sheet.sheetName" :name="sheet.name">
              <el-container>
                <el-header style="height: auto;padding-top: 20px;">
                  <el-form :model="sheet" label-width="200px">
                    <el-row>
                      <el-col :span="6">
                        <el-form-item label="表名称">
                          <el-input v-model="sheet.sheetName" @blur="blur(sheet)"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="数据库查询命令">
                          <pubList v-model="sheet.queryName"></pubList>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="表头行号">
                          <el-input-number v-model="sheet.headerRowIndex"  :step="1" :min="0" :max="65536"></el-input-number>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="有边框">
                          <el-checkbox v-model="sheet.bordered"></el-checkbox>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="6">
                        <el-form-item label="跳过行数">
                          <el-input-number v-model="sheet.skipRowCount"  :step="1" :min="0" :max="1000"></el-input-number>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="跳过列数">
                          <el-input-number v-model="sheet.skipColumnCount"  :step="1" :min="0" :max="1000"></el-input-number>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="表头行高">
                          <el-input-number v-model="sheet.headerHeight"  :step="100" :min="500" ></el-input-number>
                        </el-form-item>
                      </el-col>
                      <el-col :span="6">
                        <el-form-item label="数据行高">
                          <el-input-number v-model="sheet.rowHeight"  :step="100" :min="500"></el-input-number>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>

                </el-header>
                <el-main>
                  <el-table border :data="sheet.fields" >
                    <el-table-column type="index" fixed="left" header-align="center" align="center" label="#" width="40">
                      <template slot-scope="props">
                        {{ props.$index + 1 }}
                      </template>
                    </el-table-column>
                    <el-table-column fixed="left" header-align="center" align="center" width="60">
                      <template slot="header">
                        <el-button type="text" icon="el-icon-sort"></el-button>
                      </template>
                      <template slot-scope="props">
                        <el-button :disabled="props.$index <= 0" type="text" icon="el-icon-top" @click="sheet.fields.moveUp(props.$index)"></el-button>
                        <el-button :disabled="props.$index >= sheet.fields.length - 1" type="text" icon="el-icon-bottom" @click="sheet.fields.moveDown(props.$index)"></el-button>
                      </template>
                    </el-table-column>
                    <el-table-column label="字段名称" width="150">
                      <template slot-scope="props">
                        <el-input v-model="props.row.fieldName"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="字段显示名" width="150">
                      <template slot-scope="props">
                        <el-input v-model="props.row.displayName"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="字段类型" width="150">
                      <template slot-scope="props">
                        <mf-typeSelect v-model="props.row.typeName"></mf-typeSelect>
                      </template>
                    </el-table-column>
                    <el-table-column label="单元格宽度" width="150">
                      <template slot-scope="props">
                        <el-input-number v-model="props.row.width"  :step="100" :min="500"></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="表头字体大小" width="150">
                      <template slot-scope="props">
                        <el-input-number v-model="props.row.headerFontSize" :step="1" :min="12" :max="40" ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="单元格字体大小" width="150">
                      <template slot-scope="props">
                        <el-input-number v-model="props.row.fontSize" :step="1" :min="12" :max="40" ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="单元格格式(参照Excel单元格格式进行设置)" min-width="150">
                      <template slot-scope="props">
                        <el-input v-model="props.row.format"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column fixed="right" header-align="center" align="center" width="40">
                      <template slot="header">
                        <el-button type="text" icon="el-icon-circle-plus" @click="addField(sheet)"></el-button>
                      </template>
                      <template slot-scope="props">
                        <el-button type="text" icon="el-icon-remove" @click="sheet.fields.remove(props.row)"></el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-main>
              </el-container>
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
      <moduleList ref="moduleList" :visible.sync="showModules" :modules="modules"></moduleList>
    </el-main>
  </el-container>
</template>
<script>
import { mapGetters, mapState, mapActions } from 'vuex';
import pubList from '../components/PubSelect.vue';
import moduleList from '../components/ModuleSettings.vue';
const STORE_MODULE = {
  "name": "excelExporter",
  "actions": [
    "item",
    "create",
    "update"
  ]
};
export default {
  components: {
    pubList,
    moduleList
  },
  data() {
    return {
      newItem: false,
      showModules: false,
      showSelectFile: false,
      currentTab:'',
      files:[],
      modules: [],
      model: {
        name: "",
        template: "",
        excelFormat: "XLS",
        maxRowCountPerSheet: 1000,
        dataLoader: '',
        sheets: [],
        modules: {}
      }
    };
  },
  computed: {
    maxRowCount(){
      return this.model.excelFormat == 'XLS'? 65536:1048576;
    },
    previewLink(){
      let link = '';
      if (this.model.name) {
        link =`${this.$service.export.load.url}?exporter=${this.model.name}`;
      }
      return link;
    }
  },
  created() {
    this.loadObject();
  },
  methods: {
    ...mapActions(STORE_MODULE.name, STORE_MODULE.actions),
    loadObject() {
      let name = this.$route.params.name;
      this.model.name = name;
      this.item(name).then(response => {
        if (response.success){
          if (response.data){
            this.setModel(response.data);
          }
          else{
            this.newItem = true;
          }
        }
      });
    },
    setModel(data){
      this.model = data;
      this.model.sheets = this.model.sheets || [];
      this.model.sheets.forEach((s, i) => {
        s.name = s.sheetName;
        if (i === 0){
          this.currentTab = s.name;
        }
      })
      if (this.model.template){
        this.files = [this.model.template];
      }
      for(let key in this.model.modules){
        this.modules.push({ name: key, type: this.model.modules[key] });
      }
    },
    addField(sheet){
      sheet.fields.push({
        fieldName: '',
        displayName: '',
        typeName: 'System.String',
        width: 500,
        headerFontSize: 14,
        fontSize: 14,
        format: ''
      });
    },
    editSheet(targetName, action){
      if (action === 'add') {
        let newSheet = {
          name: `New Sheet ${this.model.sheets.length + 1}`,
          sheetName: 'New Sheet',
          queryName: '',
          headerRowIndex: 0,
          skipRowCount: 0,
          skipColumnCount: 0,
          headerHeight: 300,
          rowHeight: 300,
          bordered: false,
          fields: []
        };
        this.model.sheets.push(newSheet);
        this.currentTab = newSheet.name;
      }
      if (action === 'remove') {
        let sheets = this.model.sheets;
        let activeName = this.currentTab;
        if (activeName === targetName) {

          sheets.forEach((sheet, index) => {
            if (sheet.name === targetName) {
              let nextSheet = sheets[index + 1] || sheets[index - 1];
              if (nextSheet) {
                activeName = nextSheet.name;
              }
            }
          });
        }

        this.currentTab = activeName;
        this.model.sheets.remove(s => s.name == targetName);
      }
    },
    blur(sheet){
      if (this.currentTab == sheet.name)
        this.currentTab = sheet.sheetName;
      sheet.name = sheet.sheetName;
    },
    back() {
      this.$router.push({ name: "excelExporter" });
    },
    setTemplate(file){
      this.files = [file.fileId];
    },
    save() {
      let task = this.newItem ? this.create : this.update;
      console.log(this.$refs.moduleList);
      this.model.modules = this.$refs.moduleList.getObject();
      if (this.files && this.files.length > 0)
        this.model.template = this.files[0];
      task(this.model).then(response => {
        if (response.success) {
          this.newItem = false;
          //this.setModel(response.data);

          alert("保存成功", "消息", "success");
        } else {
          if (response.message) alert(response.message, "错误", "error");
        }
      });
    },
    preview(){
      let queryContent = {};
      this.model.sheets.forEach(sheet => {
        queryContent[sheet.queryName] = {};
      });
      this.$service.export.load({
        params: {
          exporter: this.model.name
        },
        data: {
          queryContent,
          fileName: null,
          dispositionType: null
        }
      }).then(r =>{

      });
    }
  }
};
</script>
